package BehaviorModel.iterorModel;

import java.util.ArrayList;
import java.util.Iterator;
import java.util.List;

public class InfoCollege implements College{
    List<Department> departmentList;

    private Iterator iteratorList;

    public InfoCollege(List<Department> departmentList) {
        this.departmentList = departmentList;
    }

    @Override
    public String getName() {
        return "物理系";
    }

    @Override
    public void addDepartment(Department department) {
        departmentList.add(department);
    }

    /***
     * 使用迭代器的 remove 方法: 改为使用迭代器来遍历并在需要时删除元素，迭代器提供了安全的 remove 方法来避免这个问题。
     *    for (Iterator<Department> it = departmentList.iterator(); it.hasNext(); ) {
     *        Department o = it.next();
     *        if (o.equals(department)) {
     *            it.remove();
     *        }
     *    }
     *
     * 创建要删除元素的副本: 遍历集合时，先找出所有要删除的元素，记录它们，然后在遍历完成后统一移除。
     *    List<Department> toRemove = new ArrayList<>();
     *    for (Department o : departmentList) {
     *        if (o.equals(department)) {
     *            toRemove.add(o);
     *        }
     *    }
     *    departmentList.removeAll(toRemove);
     */
    @Override
    public void removeDepartment(Department department) {
        //Java 的集合类（尤其是那些支持快速失败机制的，如 ArrayList 和 LinkedList）
        // 在迭代过程中会维护一个称为 modCount（修改计数）的字段，每次对集合进行结构性修改
        // （如添加或删除元素）时，这个计数就会增加。迭代器在迭代时会检查这个计数，
        // 如果发现迭代期间 modCount 发生了变化（即集合在迭代过程中被修改了），
        // 就会抛出 ConcurrentModificationException。
        //for (Department o : departmentList) {
        //    if (o.equals(department)){//Exception in thread "main" java.util.ConcurrentModificationException
        //        departmentList.remove(o);//效率低下,考虑交换至最后一个来移除
        //    }
        //}

        ArrayList<Department> departmentArrayList = new ArrayList<>();
        for (Department o : departmentList){
            if (o.equals(department)){
                departmentArrayList.add(o);
            }
        }

        departmentList.removeAll(departmentArrayList);
        createIterator();
    }

    @Override
    public Iterator createIterator() {
        if (iteratorList == null){
            iteratorList = new InfoIteror(departmentList);
        }else{
            InfoIteror infoIteror = (InfoIteror) this.iteratorList;
            infoIteror.setDepartments(departmentList);
        }
        return this.iteratorList;
    }
}
